package cn.keniykey.mc.viewlibrary.container;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import cn.keniykey.mc.viewlibrary.channel.AbChannelUtil;
import cn.keniykey.mc.viewlibrary.container.api.Container;
import cn.keniykey.mc.viewlibrary.packet.AbPacketUtil;

public final class ContainerPlayerListener implements Listener{
	
	public ContainerPlayerListener() {		
		AbChannelUtil.getUtil();
		AbPacketUtil.getUtil();
		for(final Player player : Bukkit.getOnlinePlayers()) {
			AbChannelUtil.getUtil().addPlayerAbPacketReceiveHandler(player, new ContainerPacketReceiveHandler());
		}
	}
	
	@EventHandler(priority = EventPriority.LOWEST)
	public void onPlayerJoin(final PlayerJoinEvent e) {
		AbChannelUtil.getUtil().addPlayerAbPacketReceiveHandler(e.getPlayer(), new ContainerPacketReceiveHandler());
	}
	@EventHandler(priority = EventPriority.MONITOR)
	public void onPlayerQuit(final PlayerQuitEvent e) {
		final Container container = Container.getViewingContainer(e.getPlayer());
		if(container == null) return;
		container.close(e.getPlayer(), false, false);
		AbChannelUtil.getUtil().removePlayerAbPacketReceiveHandler(e.getPlayer());
	}
	@EventHandler(priority = EventPriority.MONITOR,ignoreCancelled = true)
	public void onPlayerInventoryOpen(final InventoryOpenEvent e) {
		if(!(e.getPlayer() instanceof Player)) return;
		final Player player = (Player) e.getPlayer();
		final Container container = Container.getViewingContainer(player);
		if(container == null) return;
		container.close(player, false, false);
	}
}